/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.body

import com.shuyihui.rxhttp.utils.HttpLog
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.IOException

/**
 *
 * 描述：上传请求体
 * 1.具有上传进度回调通知功能<br></br>
 * 2.防止频繁回调，上层无用的刷新<br></br>
 */
class UploadProgressRequestBody : RequestBody {
    protected var delegate: RequestBody? = null
    protected var progressCallBack: ProgressResponseCallBack
    protected var countingSink: CountingSink? = null

    constructor(listener: ProgressResponseCallBack) {
        progressCallBack = listener
    }

    constructor(delegate: RequestBody?, progressCallBack: ProgressResponseCallBack) {
        this.delegate = delegate
        this.progressCallBack = progressCallBack
    }

    fun setRequestBody(delegate: RequestBody?) {
        this.delegate = delegate
    }

    override fun contentType(): MediaType? {
        return delegate!!.contentType()
    }

    /**
     * 重写调用实际的响应体的contentLength
     */
    override fun contentLength(): Long {
        return try {
            delegate!!.contentLength()
        } catch (e: IOException) {
            HttpLog.e(e.message)
            -1
        }
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        val bufferedSink: BufferedSink
        countingSink = CountingSink(sink)
        bufferedSink = countingSink!!.buffer()
        delegate!!.writeTo(bufferedSink)
        bufferedSink.flush()
    }

    protected inner class CountingSink(delegate: Sink?) : ForwardingSink(delegate!!) {
        private var bytesWritten: Long = 0
        private var contentLength: Long = 0 //总字节长度，避免多次调用contentLength()方法
        private var lastRefreshUiTime //最后一次刷新的时间
                : Long = 0

        @Throws(IOException::class)
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            if (contentLength <= 0) contentLength = contentLength() //获得contentLength的值，后续不再调用
            //增加当前写入的字节数
            bytesWritten += byteCount
            val curTime = System.currentTimeMillis()
            //每100毫秒刷新一次数据,防止频繁无用的刷新
            if (curTime - lastRefreshUiTime >= 100 || bytesWritten == contentLength) {
                progressCallBack.onResponseProgress(
                    bytesWritten,
                    contentLength,
                    bytesWritten == contentLength
                )
                lastRefreshUiTime = System.currentTimeMillis()
            }
            HttpLog.i("bytesWritten=$bytesWritten ,totalBytesCount=$contentLength")
        }
    }
}